#coding:utf-8
#包含脚本解析引擎
from geventwebsocket import WebSocketError
import socket,threading
import re
import output,poll
class MessageServer(object):#使用websocket通讯的话使用这个
    def __init__(self):
        self.observers = []#所有在线用户列表

    def _poll_to_all_user(self, msg):
        for ws in self.observers:
            try:
                ws.send(msg)
            except WebSocketError:
                self.observers.pop(self.observers.index(ws))#失败就从所有用户列表里删除
                print ws, 'is closed'
                continue
    def Return_To_User(self,usr,msg):
        usr.send(msg)#直接发送回去
class Script(object):
    """docstring for Script"""
    def __init__(self, arg):
        super(Script, self).__init__()
        self.All_CS = {}
        with open(arg) as f:
            self.GameIO = f
            self.__FindAllCodeSegment()
    def __FindAllCodeSegment(self):
        #放置入口点以及加载代码段
        All_CS = {}
        GameCode = re.findall('(\*.*?end\n)',self.GameIO.read(),re.S)
        self.FiestCS = GameCode[0]
        for i in GameCode:
            title = _txt("*","\n",i)
            print("title:",title)
            All_CS[title] = i
        self.All_CS = All_CS
    def __t(start_str, end, html):
    #获取两个字符串中间的内容
        start = html.find(start_str)
        if start >= 0:
            start += len(start_str)
            end = html.find(end, start)
            if end >= 0:
                return html[start:end].strip()
    def Return_(self,flag=""):
        self.flag = flag
        #self.args = ["mov","goto","dwave","print","bgm","lsp","bgmstop","wait","textclear","bg","if","SEL","*","end","fin","gosub","br","ld","delay","stop"]
        self.args = {
            "mov":"poll.mov",
            "goto":"poll.goto",
            "wait":"print",
            "print":"print"
            "textclear":"print",
            "bg":"poll.bg",
            "if":"poll.iif",
            "SEL":"poll.sel",
            "*":"print",
            "end":"poll.end_fin",
            "fin":"poll.end_fin",
            "gosub":"print",
            "br":"print",
            "ld":"print",
            "delay":"print",
            "stop":"print"
        }#没有打算处理的就用print跳过，有打算处理的就在poll.py加入对应的函数
        if self.flag == "" or self.flag["cs"] == "":
            #First Game!
            print("First:",self.FiestCS)

        else:
            pass
    def __Resolve(self,CodeSegment):
        #isCode = len(self.args)#计数器，作为判断用
        for line in Code:
            Left = line.split(" ",1)[0]
            Right =  line.split(" ",1)[1]
            if Left in self.args:
                #IsCODE
                O = eval(self.args[Left])
                O(Right)
            else:
                #IsString
                poll.String(Right)






